package com.lamp.connection;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;

import android.os.AsyncTask;

public class HttpConnectionManager extends HttpConnection {

	private HttpConnectionTask _loaderTask;
	private HashMap<String, HttpConnectionTask> _pendingTask = new HashMap<String, HttpConnectionManager.HttpConnectionTask>();
	private LinkedList<String> _pendingURL = new LinkedList<String>();
	private LinkedList<OnHttpConnectionLoad> _pendingInt = new LinkedList<OnHttpConnectionLoad>();

	public HttpConnectionManager() {
	}

	public void sentRequest(String _url, List<NameValuePair> _postParameters,
			OnHttpConnectionLoad load) {
		if (_url != null) {
			addRequest(_url, _postParameters, load);
		}

	}

	public void abordRequest() {
		super.requestAbort();
	}

	private void addRequest(String _url, List<NameValuePair> postParameters,
			OnHttpConnectionLoad load) {
		HttpConnectionTask task = new HttpConnectionTask(_url, postParameters);
		_pendingURL.offer(_url);
		_pendingTask.put(_url, task);
		_pendingInt.offer(load);
		if (_loaderTask == null
				|| _loaderTask.getStatus() == AsyncTask.Status.FINISHED) {
			_loaderTask = _pendingTask.get(_pendingURL.poll());
			_loaderTask.execute();
		}
	}

	class HttpConnectionTask extends AsyncTask<Void, Void, String> {

		String _url;
		List<NameValuePair> _postParameters;

		public HttpConnectionTask(String _url,
				List<NameValuePair> postParameters) {

			this._url = _url;
			this._postParameters = postParameters;

		}

		@Override
		protected String doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			return postHtml(_url, _postParameters);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (isCancelled() || result == null) {
				result = null;
			}

			OnHttpConnectionLoad load = _pendingInt.poll();

			if (load != null && result != null) {
				load.onHttpConnectionExecuted(result);
			} else {
				load.onHttpConnectionFailed();
			}

			if (!_pendingURL.isEmpty()) {
				_loaderTask = _pendingTask.get(_pendingURL.poll());
				_loaderTask.execute();
			}

		}

	}
}
